package action

import (
	"filesvr/api/fsimg/service"
	"strconv"

	"core/corestruct"
	"core/coreutil"
	"core/myerrors"
	"filesvr/api/fsimg/data"
	"filesvr/config"
	"filesvr/filesvrinfo"
	"filesvr/mongo"
	"fmt"

	"reflect"
)

type UpAction struct {
}

func (p *UpAction) Do(ctx *corestruct.HttpContext) (*data.ImgDto, error) {
	var c = ctx.Http
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		return nil, myerrors.NewByErr(err, "获取文件失败")
	}
	// 获取文件名，并创建新的文件存储
	if header.Size/1024/1024 > config.Config.File.MaxImgSize {
		return nil, myerrors.New(fmt.Sprintf("图片不能大于 %d M", config.Config.File.MaxFileSize))
	}

	var m = &mongo.File{
		Id:          coreutil.IdUtil.GetId(),
		Name:        header.Filename,
		Memo:        "",
		Size:        header.Size,
		Data:        nil,
		Gid:         coreutil.IdUtil.UuidStr(),
		FileId:      "",
		ContentType: "",
	}
	m.FileId = strconv.FormatInt(m.Id, 10)

	filedata := make([]byte, header.Size)
	_, err = file.Read(filedata)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}
	r, err := service.MainService.Save(m, &filedata, ctx)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}
	return r, nil
}

func UpActionInit() {
	var mact = &UpAction{}
	var maction = corestruct.Action{
		Method: "",

		FullUrl: service.URLPrev + "/up",
		Name:    "上传" + PAGEName,
		Ename:   "",
		Memo:    "",

		PinType:    "",
		PinIslist:  false,
		PoutType:   "",
		PoutIslist: false,
		PoutIspage: false,

		AuthType: corestruct.AuthType_Login,

		LogNeed:     false,
		LogPin:      false,
		LogPout:     false,
		LogTemplete: "",

		PrjName: filesvrinfo.PRJ_NAME,

		Value: reflect.ValueOf(mact),
	}
	coreutil.ActionUtil.Add(maction)

}
